home *** CD-ROM | disk | FTP | other *** search
/ NetNews Offline 2 / NetNews Offline Volume 2.iso / news / comp / lang / c++-part2 / 17250 < prev    next >
Encoding:
Text File  |  1996-08-05  |  1.7 KB  |  57 lines

  1. Newsgroups: comp.lang.c++
  2. Path: presby.edu!jtbell
  3. From: jtbell@presby.edu (Jon Bell)
  4. Subject: Re: const member functions..
  5. Message-ID: <DpvCqC.2As@presby.edu>
  6. Date: Sun, 14 Apr 1996 20:25:24 GMT
  7. References: <4krjlj$spn@canopus.cc.umanitoba.ca>
  8. Organization: Presbyterian College, Clinton, South Carolina USA
  9.  
  10.   <rdanse@pobox.com> wrote:
  11. >What does the const operator do when used at the end of a member
  12. >function declaration in an object class?
  13.  
  14. It signals to the compiler that that member function is guaranteed not to 
  15. change the member data of the object that it is a member of.
  16.  
  17. If you try to write a const member function that *does* change member 
  18. data, the compiler calls it an error.
  19.  
  20. If you declare an object as const, you may use only the const member
  21. functions of that object.  If you try to use a non-const member function
  22. of a const object, the compiler calls it an error. 
  23.  
  24. Example:
  25.  
  26. class Vector
  27. {
  28.   Vector(double X, double Y, double Z)   // constructor
  29.     { X_ = X; Y_ = Y; Z_ = Z };
  30.   double Length (void) const   // calculates the length of a vector
  31.     { return sqrt (X_*X_ + Y_*Y_ + Z_*Z); };
  32.   void SetVector (double X, double Y, double Z)   // sets the components 
  33.     { X_ = X; Y_ = Y; Z_ = Z };                   // of a vector 
  34.   ... etc...
  35. private
  36.   double X_, Y_, Z_;
  37. };
  38.  
  39.  
  40. int main (void)
  41. {
  42.   const Vector
  43.     g (0, 0, -9.8);   // downward acceleration of gravity, which is a
  44.                       // constant for most purposes on Earth's surface
  45.  
  46.   cout << g.Length();   // OK because Length is const
  47.  
  48.   g.SetVector(0, 0, -1.6); // not OK because SetVector is not const
  49.  
  50.   ... etc...
  51. }
  52.  
  53.  
  54. -- 
  55. Jon Bell <jtbell@presby.edu>                        Presbyterian College
  56. Dept. of Physics and Computer Science        Clinton, South Carolina USA
  57.